const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保 uploads 目录存在
const uploadDir = 'uploads/';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 指定文件存储路径
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：字段名-时间戳.扩展名
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + Date.now() + ext);
  }
})

module.exports = (opt) => {
  return multer({ storage: storage, ...opt });
}
